/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package autopecas.Telas;

import autopecas.ClasseBasica.Cliente;
import autopecas.ClasseBasica.Veiculo;
import autopecas.Dados.DadosMetodosAux;
import autopecas.Fachada.Fachada;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author NeGo
 */
public class CadastrarVeiculo extends javax.swing.JFrame {

    /**
     * Creates new form CadatrarVeiculo
     */
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        modeloTextField1 = new javax.swing.JTextField();
        corTextField2 = new javax.swing.JTextField();
        veiculoTextField3 = new javax.swing.JTextField();
        cadastrarVeiculo = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableListaVeiculos = new javax.swing.JTable();
        removerVeiculo = new javax.swing.JButton();
        jLabelCliente = new javax.swing.JLabel();
        jLabelShowCliente = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jLabelId = new javax.swing.JLabel();
        jLabelShowID = new javax.swing.JLabel();
        jButtonsalvar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Modelo :");

        jLabel2.setText("Cor :");

        jLabel3.setText("Veiculo :");

        cadastrarVeiculo.setText("Cadastrar");
        cadastrarVeiculo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cadastrarVeiculoActionPerformed(evt);
            }
        });

        jLabel4.setText("Auto Pecas São Jorge");

        jTableListaVeiculos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTableListaVeiculos);

        removerVeiculo.setText("Remover");
        removerVeiculo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removerVeiculoActionPerformed(evt);
            }
        });

        jLabelCliente.setText("Cliente:");

        jButton1.setText("Alterar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jLabelId.setText("ID");

        jButtonsalvar.setText("Salvar");
        jButtonsalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonsalvarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(23, 23, 23)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(34, 34, 34)
                                .addComponent(corTextField2))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18)
                                .addComponent(veiculoTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabelCliente))
                                .addGap(18, 18, 18)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabelShowCliente, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(modeloTextField1))))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabelId)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jLabelShowID, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButtonsalvar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jButton1))
                                .addComponent(cadastrarVeiculo, javax.swing.GroupLayout.DEFAULT_SIZE, 144, Short.MAX_VALUE)
                                .addComponent(removerVeiculo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 375, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(117, 117, 117)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 134, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(31, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel4)
                .addGap(1, 1, 1)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabelShowCliente, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(cadastrarVeiculo)
                        .addComponent(jLabelCliente)))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(removerVeiculo)
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jButtonsalvar))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 80, Short.MAX_VALUE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(modeloTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(corTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(22, 22, 22)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(veiculoTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelId)
                            .addComponent(jLabelShowID, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private Fachada fachada;
    private ArrayList<Veiculo> retorno;

    public CadastrarVeiculo(Cliente cli) {
        initComponents();
        jLabelShowCliente.setText(Long.toString(cli.getCpf()));
        fachada = new Fachada();
        refreshTable();
        jLabelShowID.setVisible(false);
        jLabelId.setVisible(false);
        jButtonsalvar.setEnabled(false);
    }

    private void cadastrarVeiculoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cadastrarVeiculoActionPerformed
        // TODO add your handling code here:
        if (DadosMetodosAux.validarNum(modeloTextField1.getText())) {
            try {

                Veiculo veiculo = new Veiculo(0, Integer.parseInt(modeloTextField1.getText()), veiculoTextField3.getText(), corTextField2.getText(), Long.parseLong(jLabelShowCliente.getText()));
                fachada.RegraCadastrar(veiculo);
                refreshTela();
                JOptionPane.showMessageDialog(rootPane, "Cadastro Realizado com sucesso");
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(rootPane, ex.getMessage());
            }
        } else {
            JOptionPane.showMessageDialog(rootPane, "Informar apenas numeros no campo modelo");
        }


    }//GEN-LAST:event_cadastrarVeiculoActionPerformed

    private void removerVeiculoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removerVeiculoActionPerformed
        // TODO add your handling code here:
        try {
            if (retorno != null) {
                if (jTableListaVeiculos.getSelectedRowCount() == 1) {
                    fachada.RegraRemover(retorno.get(jTableListaVeiculos.getSelectedRow()));
                    refreshTela();
                    JOptionPane.showMessageDialog(rootPane, "Veiculo Deletado");
                } else {
                    throw new Exception("Selecionar apenas uma linha");
                }

            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e.getMessage());
        }
    }//GEN-LAST:event_removerVeiculoActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        if (retorno != null) {
            Veiculo alterador = retorno.get(jTableListaVeiculos.getSelectedRow());
            jLabelId.setVisible(true);
            jLabelShowID.setVisible(true);
            jLabelShowID.setText(alterador.getCodigoVeiculo()+"");
            modeloTextField1.setText(alterador.getModelo()+"");
            corTextField2.setText(alterador.getCor());
            veiculoTextField3.setText(alterador.getVeiculo());
            jButtonsalvar.setEnabled(true);
            
        }


    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButtonsalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonsalvarActionPerformed
        // TODO add your handling code here:
        try{
        Veiculo alterador = new Veiculo(Integer.parseInt(jLabelShowID.getText()),Integer.parseInt(modeloTextField1.getText()) ,veiculoTextField3.getText(), corTextField2.getText(), Long.parseLong(jLabelShowCliente.getText()));
        fachada.RegraAtualizar(alterador);
        JOptionPane.showMessageDialog(rootPane, "Alterado com Sucesso");
        refreshTela();
        }catch(Exception e){
            JOptionPane.showMessageDialog(rootPane, e.getMessage());
        }
    }//GEN-LAST:event_jButtonsalvarActionPerformed
    private void refreshTable() {
        try {
            retorno = fachada.regraListar(Long.parseLong(jLabelShowCliente.getText()));
            DefaultTableModel model = new DefaultTableModel();
            model.setColumnIdentifiers(new String[]{"Codigo", "Cor", "Modelo", "Veiculo"});
            for (Veiculo veiculo : retorno) {

                model.addRow(new String[]{Integer.toString(veiculo.getCodigoVeiculo()), veiculo.getCor(), Integer.toString(veiculo.getModelo()), veiculo.getVeiculo()});

            }
            jTableListaVeiculos.setModel(model);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e.getMessage());
        }
    }
    private void refreshTela(){
        modeloTextField1.setText(null);
        corTextField2.setText(null);
        veiculoTextField3.setText(null);
        refreshTable();
        jLabelShowID.setVisible(false);
        jLabelId.setVisible(false);
        jButtonsalvar.setEnabled(false);
    }
    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cadastrarVeiculo;
    private javax.swing.JTextField corTextField2;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButtonsalvar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabelCliente;
    private javax.swing.JLabel jLabelId;
    private javax.swing.JLabel jLabelShowCliente;
    private javax.swing.JLabel jLabelShowID;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableListaVeiculos;
    private javax.swing.JTextField modeloTextField1;
    private javax.swing.JButton removerVeiculo;
    private javax.swing.JTextField veiculoTextField3;
    // End of variables declaration//GEN-END:variables

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CadastrarVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CadastrarVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CadastrarVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CadastrarVeiculo.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CadastrarVeiculo(new Cliente(new String(), new Long(""), new ArrayList<Veiculo>())).setVisible(true);
            }
        });
    }

}
